package com.xls.box2023.network;

import com.lzz.bottomencapsulation.utils.LUtils;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.ObservableTransformer;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;


//LifecycleEventObserver 新的

// 废弃用法
//public class RxLifecycle implements LifecycleObserver {
//    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
//    void destroy() {
//        Logger.d("=====RxLifecycle====destroy==========");
//    }
//}

// androidx的生命周期感知 + rxjava的转换器 此类的实例也是 Observable 了，可以参与Rx的流中了
// best design here
public class RxLifecycle<T> implements LifecycleEventObserver, ObservableTransformer<T, T> {

    // 管理所有的Observable(Disposable)对象
    // 页面onDestroy时统一删除，防止页面内存泄露
    final CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {

//        Logger.d("RxLifecycle=======" + source);
        LUtils.d("RxLifecycle=======" + event);

        if (event == Lifecycle.Event.ON_DESTROY) {
            if (!compositeDisposable.isDisposed()) {
                compositeDisposable.dispose();
            }
        } else if (event == Lifecycle.Event.ON_CREATE) {
        }

    }

    @Override
    public @io.reactivex.rxjava3.annotations.NonNull ObservableSource<T> apply(@io.reactivex.rxjava3.annotations.NonNull Observable<T> upstream) {
        return upstream.doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Throwable {
                // Observable subscribe连接Observer的时候，add进来
                compositeDisposable.add(disposable);

                LUtils.d("disposable size:" + compositeDisposable.size());
            }
        });
    }


    // bind 页面
    // 这个操作也可以加到Transformer中去
    public static <T> RxLifecycle<T> bindRxLifecycle(LifecycleOwner lifecycleOwner) {
        RxLifecycle<T> lifecycle = new RxLifecycle<>();
        lifecycleOwner.getLifecycle().addObserver(lifecycle);
        return lifecycle;
    }
}
